import React, {Component, createRef} from "react";
import {View, StyleSheet, SafeAreaView, Text, FlatList, TouchableOpacity, SectionList, Image, Platform, ActivityIndicator} from "react-native";
import {connect} from "react-redux";
import {Dispatch} from "redux";
import Header from "../components/Header";
import {COLORS, icons, SIZES} from "../constants";
import {OrderActions} from "../modules/OrderModule";
import {RootState} from "../types";
import {dishItemI, sectionsItemT} from "../types/OrderState";
import {ptd} from "../utils/styleUtil";
// @ts-ignore
import RCTNativeAppEventEmitter from "react-native/Libraries/EventEmitter/RCTNativeAppEventEmitter";
import {EMIT_ORDER_NOW} from "../constants/emits";
import Toast from "react-native-root-toast";
import {LOADING_ORDER} from "../constants/loadingKey";

interface OrderPageProps {
    navigation: any;
    orderMap: {[key: string]: any};
    sectionsData: sectionsItemT[];
    menuData: string[];
    addDish: (dish: dishItemI) => void;
    deleteDish: (dish: dishItemI) => void;
    orderNow: () => void;
    loadingOrder: boolean;
}

interface OrderPageState {
    selectedIdx: number;
}

class OrderPage extends Component<OrderPageProps, OrderPageState> {
    constructor(props: OrderPageProps) {
        super(props);
        this.state = {
            selectedIdx: 0,
        };
    }

    sectionList: any = createRef();
    scrollBegin = false;
    orderNowListener: any;

    componentDidMount() {
        this.orderNowListener = RCTNativeAppEventEmitter.addListener(EMIT_ORDER_NOW, () => {
            Toast.show("Order Success", {
                duration: 500,
                position: SIZES.height - 200,
                onHidden: () => {},
            });
        });
    }
    componentWillUnmount() {
        this.orderNowListener.remove();
    }

    goBack = () => {
        this.props.navigation.goBack();
    };

    clickOnItem(index: number) {
        this.setState({selectedIdx: index});
        if (this.sectionList) {
            this.sectionList.current.scrollToLocation({
                sectionIndex: index,
                itemIndex: 0,
                viewPosition: 0,
                animated: Platform.OS === "ios",
            });
        }
    }
    _renderMenuItem = ({item, index}: any) => {
        return (
            <TouchableOpacity
                key={index}
                style={[
                    styles.menuItemWra,
                    index === this.state.selectedIdx && {
                        backgroundColor: "#ffffff88",
                    },
                ]}
                onPress={() => this.clickOnItem(index)}
            >
                <Text numberOfLines={2} style={[styles.menuItemTxt, index === this.state.selectedIdx && {color: "#fff"}]}>
                    {item}
                </Text>
            </TouchableOpacity>
        );
    };
    renderSectionItem = ({item}: any) => {
        const {addDish, orderMap, deleteDish} = this.props;

        const orderItem = orderMap["id" + item.id];

        return (
            <View style={styles.sectionItemWra}>
                <Image source={item.img} style={styles.sectionImg} />
                <View style={styles.sectionItemRightWra}>
                    <Text numberOfLines={2} style={{color: "#fff", fontSize: 15, width: ptd(160)}}>
                        {item.name}
                    </Text>
                    <Text
                        numberOfLines={3}
                        style={{
                            color: "#ffffff88",
                            fontSize: 12,
                            width: ptd(160),
                            lineHeight: 19,
                        }}
                    >
                        {item.content}
                    </Text>
                    <View style={styles.sectionItemBottomWra}>
                        <View style={{flexDirection: "row", alignItems: "center"}}>
                            <Text style={[styles.sectionItemPriceTxt, {position: "relative", top: 1}]}>$</Text>
                            <Text style={[styles.sectionItemPriceTxt, {fontSize: 20, marginLeft: 2}]}>{item.price.toFixed(2)}</Text>
                        </View>
                        <View style={{flexDirection: "row", alignItems: "center", height: 30}}>
                            {!!orderItem && (
                                <>
                                    <TouchableOpacity onPress={() => deleteDish(item)}>
                                        <Image source={icons.deleteCircle} style={styles.sectionIconDelete} />
                                    </TouchableOpacity>
                                    <Text
                                        style={{
                                            color: "#ffffffaa",
                                            fontSize: 18,
                                            marginHorizontal: 8,
                                        }}
                                    >
                                        {orderItem.num}
                                    </Text>
                                </>
                            )}
                            <TouchableOpacity onPress={() => addDish(item)}>
                                <Image source={icons.add} style={styles.sectionIconAdd} />
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </View>
        );
    };
    renderSectionHeader = ({section}: any) => {
        return (
            <View style={styles.sectionHeaderWra}>
                <Text style={{color: "#fff", fontSize: 14}}>{section.title}</Text>
            </View>
        );
    };
    itemOnChanged = ({viewableItems}: any) => {
        const {menuData} = this.props;
        if (!this.scrollBegin && Platform.OS === "ios") {
            return;
        }
        let firstItem = viewableItems[0];
        if (firstItem && firstItem.section) {
            let name = firstItem.section.title;
            let idx = menuData.indexOf(name);
            this.setState({selectedIdx: idx});
        }
    };
    render() {
        const {sectionsData, menuData, orderMap, orderNow, loadingOrder} = this.props;
        const orderMapKes = Object.keys(orderMap);
        let totalPrice = 0;
        orderMapKes.forEach(item => {
            totalPrice += orderMap[item].price * orderMap[item].num;
        });
        return (
            <View style={{flex: 1, backgroundColor: COLORS.black}}>
                <Header goBack={this.goBack} title="ORDER" />
                <View style={styles.listWra}>
                    <View style={{width: ptd(80)}}>
                        <FlatList data={menuData} keyExtractor={(_, index) => index + ""} renderItem={this._renderMenuItem} />
                    </View>
                    <SectionList
                        ref={this.sectionList}
                        keyExtractor={(_, index) => index + ""}
                        sections={sectionsData}
                        renderItem={this.renderSectionItem}
                        renderSectionHeader={this.renderSectionHeader}
                        stickySectionHeadersEnabled
                        showsVerticalScrollIndicator={false}
                        onMomentumScrollBegin={() => {
                            this.scrollBegin = true;
                        }}
                        onMomentumScrollEnd={() => {
                            this.scrollBegin = false;
                        }}
                        onViewableItemsChanged={this.itemOnChanged}
                    />
                </View>
                <SafeAreaView>
                    <View style={styles.bottomWra}>
                        <Image source={icons.cart} style={[styles.cartIcon, orderMapKes.length !== 0 && {tintColor: COLORS.primary}]} />
                        <View style={styles.bottomTxtWra}>
                            <View style={{flexDirection: "row"}}>
                                <Text
                                    style={{
                                        color: COLORS.primary,
                                        marginTop: 4,
                                    }}
                                >
                                    $
                                </Text>
                                <Text style={{color: COLORS.primary, fontSize: 18, marginLeft: 2}}>{totalPrice.toFixed(2)}</Text>
                            </View>
                            <Text style={{color: "#ffffff88", fontSize: 10}}>免配送费</Text>
                        </View>
                        <TouchableOpacity disabled={orderMapKes.length === 0 || loadingOrder} style={[styles.orderBtnWra, orderMapKes.length === 0 && {backgroundColor: "#ffffff66"}]} onPress={orderNow}>
                            {loadingOrder && <ActivityIndicator color="#fff" style={{marginRight: 5}} />}
                            <Text style={styles.orderBtnTxt}>ORDER NOW</Text>
                        </TouchableOpacity>
                    </View>
                </SafeAreaView>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    listWra: {
        flex: 1,
        flexDirection: "row",
    },
    menuListWra: {
        width: ptd(80),
    },
    bottomWra: {
        height: 60,
        alignItems: "center",
        flexDirection: "row",
        paddingHorizontal: SIZES.SPACE_S,
    },
    menuItemWra: {
        height: 60,
        justifyContent: "center",
        alignItems: "center",
        paddingHorizontal: ptd(8),
    },
    menuItemTxt: {
        color: "#ffffff88",
    },
    sectionHeaderWra: {
        height: 40,
        justifyContent: "center",
        paddingHorizontal: SIZES.SPACE_S,
        backgroundColor: COLORS.black,
    },
    sectionItemWra: {
        flexDirection: "row",
        marginBottom: 10,
        paddingHorizontal: SIZES.SPACE_S,
    },
    sectionImg: {
        width: ptd(90),
        height: ptd(125),
    },
    sectionItemRightWra: {
        marginLeft: ptd(10),
        justifyContent: "space-between",
    },
    sectionIconAdd: {
        tintColor: COLORS.primary,
        width: ptd(20),
        height: ptd(20),
    },
    sectionItemBottomWra: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
    },
    sectionItemPriceTxt: {
        color: COLORS.primary,
        fontSize: 15,
    },
    cartIcon: {
        width: 40,
        height: 40,
    },
    bottomTxtWra: {
        marginLeft: 12,
    },
    orderBtnWra: {
        marginLeft: "auto",
        backgroundColor: COLORS.primary,
        width: 150,
        height: 38,
        borderRadius: 20,
        justifyContent: "center",
        alignItems: "center",
        flexDirection: "row",
    },
    orderBtnTxt: {
        color: "#fff",
    },
    sectionIconDelete: {
        width: 25,
        height: 25,
    },
});

const mapStateToProps = (state: RootState) => ({
    orderMap: state.app.order.orderMap,
    sectionsData: state.app.order.sectionsData,
    menuData: state.app.order.sectionsData.map(item => item.title),
    loadingOrder: !!state.loading[LOADING_ORDER],
});
const mapDispatchToProps = (dispatch: Dispatch) => ({
    addDish(dish: dishItemI) {
        dispatch(OrderActions.addDish(dish));
    },
    deleteDish(dish: dishItemI) {
        dispatch(OrderActions.deleteDish(dish));
    },
    orderNow() {
        dispatch(OrderActions.orderNow());
    },
});

export default connect(mapStateToProps, mapDispatchToProps)(OrderPage as any);
